using MediatR;
using WorkOrder.Domain;
using WorkOrder.Domain.DTOs;
using System.Text.Json;
using B.S.BaseData.Api.Read.Command.OrderCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;

namespace B.S.BaseData.Api.Read.CommandHandler.OrderCommandHandler
{
    /// <summary>
    /// 获取处方流转订单详情处理器
    /// </summary>
    public class GetPrescriptionOrderDetailHandler : IRequestHandler<GetPrescriptionOrderDetailCommand, APIResult<PrescriptionOrderDto>>
    {
        private readonly IBaseRepository<PrescriptionOrder> _prescriptionRepository;
        private readonly IBaseRepository<PrescriptionMedicine> _medicineRepository;

        public GetPrescriptionOrderDetailHandler(
            IBaseRepository<PrescriptionOrder> prescriptionRepository,
            IBaseRepository<PrescriptionMedicine> medicineRepository)
        {
            _prescriptionRepository = prescriptionRepository;
            _medicineRepository = medicineRepository;
        }

        public Task<APIResult<PrescriptionOrderDto>> Handle(GetPrescriptionOrderDetailCommand request, CancellationToken cancellationToken)
        {
            APIResult<PrescriptionOrderDto> result = new APIResult<PrescriptionOrderDto>();
            result.Code = ApiEnum.Success;
            result.Msg = "查询成功";

            // 查找处方订单
            var prescriptionOrder = _prescriptionRepository.GetAll()
                .FirstOrDefault(p => p.OrderNumber == request.OrderNumber && p.IsDelete == false);

            if (prescriptionOrder == null)
            {
                // 如果没有找到数据，生成测试数据
                prescriptionOrder = GenerateTestDetailData(request.OrderNumber);
            }

            // 查找药品明细
            var medicines = _medicineRepository.GetAll()
                .Where(m => m.OrderNumber == request.OrderNumber)
                .ToList();

            if (!medicines.Any())
            {
                // 如果没有药品数据，生成测试数据
                medicines = GenerateTestMedicineData(request.OrderNumber);
            }

            // 转换为DTO
            var prescriptionOrderDto = new PrescriptionOrderDto
            {
                OrderNumber = prescriptionOrder.OrderNumber,
                PrescriptionNumber = prescriptionOrder.PrescriptionNumber,
                OrderStatus = prescriptionOrder.OrderStatus,
                PrescriptionStatus = prescriptionOrder.PrescriptionStatus,
                PurchaseMethod = prescriptionOrder.PurchaseMethod,
                DispenseStatus = prescriptionOrder.DispenseStatus,
                TotalAmount = prescriptionOrder.TotalAmount,
                CouponAmount = prescriptionOrder.CouponAmount,
                ActualPayment = prescriptionOrder.ActualPayment,
                CreateTime = prescriptionOrder.CreateTime,
                PaymentMethod = prescriptionOrder.PaymentMethod,
                PaymentTime = prescriptionOrder.PaymentTime,
                PatientName = prescriptionOrder.PatientName,
                PatientGender = prescriptionOrder.PatientGender,
                PatientAge = prescriptionOrder.PatientAge,
                PatientPhone = prescriptionOrder.PatientPhone,
                Disease = prescriptionOrder.Disease,
                LiverFunction = prescriptionOrder.LiverFunction,
                KidneyFunction = prescriptionOrder.KidneyFunction,
                AllergyHistory = prescriptionOrder.AllergyHistory,
                PregnancyStatus = prescriptionOrder.PregnancyStatus,
                SymptomDescription = prescriptionOrder.SymptomDescription,
                SelectedMedications = prescriptionOrder.SelectedMedications,
                PrescriptionInfoNumber = prescriptionOrder.PrescriptionInfoNumber,
                PrescriptionDate = prescriptionOrder.PrescriptionDate,
                PrescriptionStatusDescription = prescriptionOrder.PrescriptionStatusDescription,
                DoctorName = prescriptionOrder.DoctorName,
                Department = prescriptionOrder.Department,
                PreliminaryDiagnosis = prescriptionOrder.PreliminaryDiagnosis,
                TreatmentAdvice = prescriptionOrder.TreatmentAdvice,
                UserName = prescriptionOrder.UserName,
                Remarks = prescriptionOrder.Remarks,
                UpdateTime = prescriptionOrder.UpdateTime,
                Medicines = medicines.Select(m => new PrescriptionMedicineDto
                {
                    Id = m.Id,
                    MedicineName = m.MedicineName,
                    Specification = m.Specification,
                    Quantity = m.Quantity,
                    UnitPrice = m.UnitPrice,
                    Usage = m.Usage,
                    MedicineType = m.MedicineType,
                    IsPrescriptionDrug = m.IsPrescriptionDrug
                }).ToList()
            };

            result.Data = prescriptionOrderDto;
            return Task.FromResult(result);
        }

        /// <summary>
        /// 生成测试详情数据
        /// </summary>
        /// <param name="orderNumber">订单编号</param>
        /// <returns></returns>
        private PrescriptionOrder GenerateTestDetailData(string orderNumber)
        {
            return new PrescriptionOrder
            {
                OrderNumber = orderNumber,
                PrescriptionNumber = orderNumber,
                OrderStatus = "待支付",
                PrescriptionStatus = "审核通过",
                PurchaseMethod = "-",
                DispenseStatus = "-",
                TotalAmount = 200,
                CouponAmount = 10,
                ActualPayment = 190,
                CreateTime = DateTime.Parse("2020-03-04 11:08:18"),
                PaymentMethod = null,
                PaymentTime = null,
                PatientName = "田田",
                PatientGender = "男",
                PatientAge = 43,
                PatientPhone = "18812341235",
                Disease = "高血压",
                LiverFunction = "正常",
                KidneyFunction = "正常",
                AllergyHistory = "无",
                PregnancyStatus = "无",
                SymptomDescription = "高血压,目前吃络活喜苯磺酸氨氯地平片,病情稳定,没有不良反应",
                SelectedMedications = "苯磺酸氨氯地平片×1盒，琥珀酸美托洛尔缓释片×3盒",
                PrescriptionInfoNumber = "20200405121300",
                PrescriptionDate = DateTime.Parse("2020-04-05 12:20:11"),
                PrescriptionStatusDescription = "审核通过",
                DoctorName = "张三",
                Department = "心内科",
                PreliminaryDiagnosis = "原发性高血压",
                TreatmentAdvice = "检测血压,适当运动",
                PrescriptionDetails = "{\"medicines\":[{\"name\":\"苯磺酸氨氯地平片\",\"specification\":\"5mg*7片/盒\",\"quantity\":1,\"usage\":\"口服，每天一次\"}]}",
                UserName = "user001",
                Remarks = "",
                UpdateTime = DateTime.Parse("2020-04-05 12:20:11"),
                IsDelete = false
            };
        }

        /// <summary>
        /// 生成测试药品数据
        /// </summary>
        /// <param name="orderNumber">订单编号</param>
        /// <returns></returns>
        private List<PrescriptionMedicine> GenerateTestMedicineData(string orderNumber)
        {
            return new List<PrescriptionMedicine>
            {
                new PrescriptionMedicine
                {
                    Id = 1,
                    OrderNumber = orderNumber,
                    MedicineName = "苯磺酸氨氯地平片 (络活喜)",
                    Specification = "规格: 5mg*7片/盒",
                    Quantity = 1,
                    UnitPrice = 25,
                    Usage = "用药情况: 正在服用;口服,每天一次,每次1片,用药21天",
                    MedicineType = "处方药",
                    IsPrescriptionDrug = true
                },
                new PrescriptionMedicine
                {
                    Id = 2,
                    OrderNumber = orderNumber,
                    MedicineName = "琥珀酸美托洛尔缓释片 (倍他乐克)",
                    Specification = "规格: 47.5mg*7片/盒",
                    Quantity = 3,
                    UnitPrice = 25,
                    Usage = "用药情况: 正在服用;口服,每天一次,每次1片,用药21天",
                    MedicineType = "处方药",
                    IsPrescriptionDrug = true
                }
            };
        }
    }
} 